from fastapi import APIRouter
from pydantic.fields import T
from utils import AddDay,CalDay
from models import Cards, FineInfo, db, Book,BorrowInfoQuery,BorrowInfo
import os
from datetime import datetime
from utils import CalDay
#test
#注释方法初始化
card_router = APIRouter()
path = os.getcwd()
with open(path+'/routers/borrow_info/readme.md','r',encoding='utf-8') as f:
    openapi_desc = f.read().split('------')

borrow_info_router = APIRouter()
# 创建借阅信息
@borrow_info_router.get('/borrowBook', summary='创建借阅信息', tags=["借阅信息相关接口"],description=openapi_desc[0])
async def createBorrow_Info(card_id: str, book_id: str):
    # 创建返回值信息的初始值
    success = False  # 是否成功创建
    msg = "借阅成功"  # 返回信息
    # 查找借阅者信息
    reader = db.cards.find_one({"card_id": card_id})
    if reader:
        reader = Cards(**reader)
        if reader.available_status:
            book = db.books.find_one({"book_id": book_id})
            if book:
                book = Book(**book)
                if book.available_status:
                    borrow = {}
                    borrow["book_id"] = book.book_id
                    borrow["book_name"] = book.book_name
                    borrow["reader_name"] = reader.reader_name
                    borrow["card_id"] = reader.card_id
                    borrow["renew_num"] = 0
                    borrow["borr_date"] = datetime.now().strftime(
                        '%Y-%m-%d')  # 现在
                    borrow["due_date"] = str(
                        AddDay(datetime.now().strftime('%Y-%m-%d'), 10)).split(" ")[0]
                    borrow["return_status"] = False
                    print(borrow)
                    db.borrow_info.insert_one(borrow)
                    db.books.update({"book_id": book_id},{"$set":{"available_status": False}})
                    success = True
                else:
                    msg = "此书不在库"
            else:
                msg = "不存在此书"
        else:
            msg = "您的卡无法使用"
    else:
        msg = "查无此人"
    return {'success': success, 'msg': msg}

# 模糊查询借阅信息
@borrow_info_router.post('/queryBorrInfo',summary='模糊查询借阅信息', tags=["借阅信息相关接口"],description=openapi_desc[1])
async def queryBorrinfo(borrowinfo:BorrowInfoQuery):
    page = borrowinfo.page
    size = borrowinfo.size
    skip = size * (page - 1)
    queryDate = {
            "book_id": {"$regex": borrowinfo.book_id},
            "book_name": {"$regex": borrowinfo.book_name},
            "card_id": {"$regex": borrowinfo.card_id},
            "reader_name": {"$regex":borrowinfo.reader_name}}
    if borrowinfo.return_status=="true":  #查询对应状态
        queryDate["return_status"]=True
    elif borrowinfo.return_status=="false":
        queryDate["return_status"]=False
    dataCount = db.borrow_info.find(queryDate).count()
    res = db.borrow_info.find(queryDate).limit(size).skip(skip)
    res=list(res)
    for i in res:
        i.pop("_id")
    return {'data': res, 'data_count': dataCount}

# 图书续借
@borrow_info_router.get("/renewBook",summary="图书续借",tags=["续借相关接口"],description=openapi_desc[2])
async def renewBook(book_id: str):
    print(book_id)
    success = False  # 是否成功创建
    msg = "续借成功"  # 返回信息
    book = db.borrow_info.find_one({"book_id": book_id})

    if book:
        card=db.cards.find_one({"card_id":book["card_id"]})
        if card["available_status"]:
            if book["renew_num"] <3:
                success=True
                i = int(book["renew_num"])+1
                db.borrow_info.update({"book_id": book_id},{"$set":{"renew_num": i,"due_date":AddDay(datetime.now().strftime('%Y-%m-%d'),20)}})
            else:
                msg="超过续借次数"
        else:
            msg="卡片无法使用,请缴纳罚金"
    else:
        msg="书本归还错误"
    return {'success': success, 'msg': msg}


    # 图书归还

@borrow_info_router.get("/returnBook",summary="图书归还",tags=["借阅信息相关接口"])
async def returnBook(book_id:str):
    success=True
    msg="还书成功"
    now = datetime.now()
    today=now.strftime("%Y-%m-%d")
    borrow=db.borrow_info.find_one({"book_id":book_id,"return_status":False})

    if borrow:
        borrow=BorrowInfo(**borrow)
        fine=db.fine_info.find_one({"book_id":book_id,"handle_status":False})
        if fine:
            success=False
            msg="还书失败（有罚金未缴纳）"
        else:
            db.borrow_info.update_one({"book_id":borrow.book_id,"return_status":False},{"$set":{"return_status":True,"return_date":today}})
            db.books.update_one({"book_id":borrow.book_id},{"$set":{"available_status":True}})
    else:
        success=False
        msg="还书失败（未能找到借阅信息）"

    return {'success':success,'msg':msg}